package top.liuyao.lab.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){

        return new DruidDataSource();
    }

    @Bean
    //后台监控功能
    //因为SpringBoot内置了Servlet容器，所以没有Web.xml，替代方法：ServletRegistrationBean
    public ServletRegistrationBean statViewServlet(){

        ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        //后台需要有人登陆，账号密码配置
        HashMap<String,String> map = new HashMap<>();
        //增加配置
        map.put("loginUsername","admin");//登陆的key，是固定的，不能自己定义成其他的
        map.put("loginPassword","123456");

        //允许谁可以访问
        map.put("allow","");

        bean.setInitParameters(map);//初始化参数
        return bean;
    }
    @Bean
    //filter
    public FilterRegistrationBean WebStartFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean<>();
        //设置过滤器
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求
        Map<String,String> filters = new HashMap<>();
        //这些东西不进行统计
        filters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(filters);

        return bean;
    }
}

